package fr.unice.guitartools.recorder;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.media.AudioRecord;

public class AudioRecorderThread extends Thread{

	
	public boolean isRecording;
	private AudioRecord audioRecord;
	private int bufferSize;
	private int sampleRate;
	private String fileName;
	
	public AudioRecorderThread(int inAudioSource, 
			int inSampleRate, int inAudioFormat,
			int inEncoding, int inBufferSize, String inFileName){
		super();
		isRecording = false;
		bufferSize = inBufferSize;
		sampleRate = inSampleRate;
		fileName = inFileName;
		audioRecord = new AudioRecord(inAudioSource,
				sampleRate, inAudioFormat,
				inEncoding, bufferSize);
	}
	
	public void StopRecording(){
		isRecording = false;
		audioRecord.stop();
		stop();
	}
	
	@Override
	public void run() {
		audioRecord.startRecording();
		isRecording = true;
		writeAudioDataToFile();
	}
	
	
	/**
	 * this method write the audio date in a file
	 */
	private void writeAudioDataToFile(){
		byte[] bArray = new byte[bufferSize];
		String l_filename = fileName + ".tmp";
		FileOutputStream os = null;
		
		try {
			os = new FileOutputStream(l_filename);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int read = 0;
		
		if(null != os){
			while(isRecording){
				read = audioRecord.read(bArray,0, bufferSize);
				
				if(AudioRecord.ERROR_INVALID_OPERATION != read){
					try {
						os.write(bArray);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
